﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JBeamLibrary.Tools;
using JBeamLibrary.VehicleParts.Interfaces;
using Newtonsoft.Json.Linq;

namespace JBeamLibrary.VehicleParts.Elements
{
    public class Flexbody : VehicleElement
    {
        #region Fields

        private readonly List<string> _groups = new List<string>();
        private readonly List<string> _nonFlexMaterials = new List<string>();

        #endregion

        #region Properties

        public string Mesh { get; set; }

        public List<string> Groups { get { return _groups; } }

        public List<string> NonFlexMaterials { get { return _nonFlexMaterials; } }

        #endregion

        #region CTORs

        public Flexbody()
        {
        }

        public Flexbody(string mesh, params string[] groups)
        {
            Mesh = mesh;
            Groups.AddRange(groups);
        }

        #endregion

        #region Methods

        public override IVehicleElement FromJBeam(JToken token)
        {
            var arr = token as JArray;
            if (arr == null) return this;

            Mesh = token[0].FromJBeam<string>();
            var arrays = token.Children<JArray>();
            if (arrays.Any())
                Groups.AddRange(arrays.ElementAt(0).Values<string>());
            if (arrays.Count() > 1)
                NonFlexMaterials.AddRange(arrays.ElementAt(1).Values<string>());

            return this;
        }

        public override JToken ToJBeam()
        {
            var elemArray = new JArray { Mesh };
            var elemFlexbody = new JArray(Groups);
            var elemNonFlexMaterials = new JArray(NonFlexMaterials);
            if (elemFlexbody.Count > 0) elemArray.Add(elemFlexbody);
            if (elemNonFlexMaterials.Count > 0) elemArray.Add(elemNonFlexMaterials);
            return elemArray;
        }

        public override string ToString()
        {
            return string.Format("Mesh: {0}", Mesh);
        }

        #endregion
    }
}
